package org.springsource.controllers;

import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springsocial.domain.ExtendedTweet;
import org.springsocial.domain.Player;
import org.springsocial.domain.Team;
import org.springsocial.nullobjects.NullPlayer;
import org.springsocial.services.PlayerService;
import org.springsocial.services.TeamService;
import org.springsource.util.ActiveTweeter;
import org.springsource.util.OrderExpression;

@Controller
public class TeamController {
	@Autowired
	private TeamService teamService;
	
	@Autowired
	private PlayerService playerService;
	
	@RequestMapping(value = "/team", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	Team save(Principal currentUser, Model model,@RequestBody Team team) {
		return team;
	}

	@RequestMapping(value = "/team/{name}", method = RequestMethod.GET)
	public String home(Principal currentUser, Model model, @PathVariable String name) {
		Team team = teamService.getTeamWithPlayers(name);
		model.addAttribute("currentTeam",team);
		model.addAttribute("players",team.getPlayers());
		Map<String,List<ExtendedTweet>> map = new TreeMap<String,List<ExtendedTweet>>();
		for(Player player : team.getPlayers()){
			Player playerWithTweets = playerService.getPlayerWithTweets(player.getId(),ActiveTweeter.ACTIVE);
			if (!(playerWithTweets instanceof NullPlayer)) {
				map.put(playerWithTweets.getFirstName()+player.getLastName(), playerWithTweets.getOrderedTweets(OrderExpression.DESC));
				model.addAttribute("tweets", map);
			}
		}
		
		return "team.home";
	}

	@RequestMapping(value = "/{countryCode}/team", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	List<Team> getByName(Principal currentUser, Model model,
			@PathVariable String countryCode) {
		return teamService.getTeamsByCountry(countryCode);
	}
	
	@RequestMapping(value = "/level/{levelName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	List<Team> getAllByLevelName(Principal currentUser, Model model,
			@PathVariable String levelName) {
		return teamService.getTeamsByLevelName(levelName);
	}
	
}
